import { Button, Form, Input, Table } from "antd";
import type { ColumnsType } from "antd/es/table";
import { PlusIcon, UserIcon } from "lucide-react";
import { useEffect, useState } from "react";
import { apiDepartmentsUsers, apiJobPositionsList, apiRolesList } from "~/api";
import { Enum_UserEmployeeType } from "~/common/enum/user.enum";
import Divider from "~/components/ui/divider";
import Filter from "~/components/ui/filter";
import Title from "~/components/ui/title";
import { useTableHeight } from "~/hooks/useTableHeight";
import type { IPageData } from "~/types/common";
import type { IFilter, IUserEmployee } from "~/types/manage/system/user";
import Empty from "./manage/system/empty";
import Department from "./manage/system/user/department";
import UserEmployeeModal from "./manage/system/user/user-employee-modal";

export default function Page() {
  const [filterForm] = Form.useForm<IFilter>();
  const [userList, setUserList] = useState<IPageData<IUserEmployee> | null>(
    null,
  );
  const tableHeight = useTableHeight(351);
  const [loading, setLoading] = useState(false);
  const [curSelectDepartmentId, setCurSelectDepartmentId] = useState<number>(0);
  const [modalVisible, setModalVisible] = useState(false);
  const [editUserEmployee, setEditUserEmployee] =
    useState<IUserEmployee | null>(null);

  const [jobPositionMap, setJobPositionMap] = useState<Map<number, string>>();
  const [roleMap, setRoleMap] = useState<Map<number, string>>();

  const _fetch = {
    init: async () => {
      const [jobPositionList, roleList] = await Promise.all([
        apiJobPositionsList(),
        apiRolesList(),
      ]);
      setJobPositionMap(
        new Map(jobPositionList.map((item) => [item.id, item.name])),
      );
      setRoleMap(new Map(roleList.map((item) => [item.id, item.name])));
    },
    users: async (departmentId: number, filter: IFilter) => {
      setLoading(true);
      const resp = await apiDepartmentsUsers(departmentId, filter);
      setUserList(resp);
      setLoading(false);
    },
  };

  const _handler = {
    addUser: () => {
      setModalVisible(true);
      setEditUserEmployee(null);
    },
    editUser: (user: IUserEmployee) => {
      setModalVisible(true);
      setEditUserEmployee(user);
    },
  };

  const _ui: {
    tableColumns: ColumnsType<IUserEmployee>;
  } = {
    tableColumns: [
      {
        title: "序号",
        dataIndex: "index",
        fixed: "left",
        width: 80,
        render: (_, __, index) => {
          return index + 1;
        },
      },
      {
        title: "姓名",
        dataIndex: ["employee", "name"],
        fixed: "left",
        width: 100,
      },
      {
        title: "职位",
        dataIndex: ["employee", "jobPositionId"],
        width: 100,
        render: (value) => {
          return jobPositionMap?.get(value) || "";
        },
      },
      {
        title: "邮箱",
        dataIndex: "email",
        width: 120,
      },
      {
        title: "手机号",
        dataIndex: "mobile",
        width: 120,
      },
      {
        title: "类型",
        dataIndex: ["employee", "type"],
        width: 100,
        render: (value) => {
          switch (value) {
            case Enum_UserEmployeeType.FULL_TIME:
              return "全职";
            case Enum_UserEmployeeType.PART_TIME:
              return "兼职";
            case Enum_UserEmployeeType.INTERN:
              return "实习生";
            default:
              return value;
          }
        },
      },
      {
        title: "角色",
        dataIndex: ["roleIds"],
        width: 100,
        render: (value: number[]) => {
          return value.map((item) => roleMap?.get(item) || "").join(",");
        },
      },
      {
        title: "操作",
        key: "action",
        fixed: "right",
        width: 100,
        render: (_, record) => {
          return (
            <div className="flex items-center justify-end gap-2">
              <Button
                type="link"
                onClick={() => {
                  _handler.editUser(record);
                }}
              >
                编辑
              </Button>
            </div>
          );
        },
      },
    ],
  };

  useEffect(() => {
    if (!curSelectDepartmentId) {
      return;
    }
    filterForm.resetFields();
    const filter = filterForm.getFieldsValue(true);
    _fetch.users(curSelectDepartmentId, filter);
  }, [curSelectDepartmentId]);

  useEffect(() => {
    _fetch.init();
  }, []);

  return (
    <>
      <div className="flex h-full w-full gap-4">
        <div className="flex h-full w-[240px] flex-col gap-4">
          <Department
            onSelectDepartment={(departmentId: number) => {
              setCurSelectDepartmentId(departmentId);
            }}
          />
        </div>
        <Divider />
        <div className="flex flex-1 flex-col gap-4 overflow-hidden">
          {curSelectDepartmentId ? (
            <>
              <Title
                title="人员"
                buttonGroups={[
                  <Button
                    type="primary"
                    onClick={() => {
                      _handler.addUser();
                    }}
                  >
                    <PlusIcon size={18} />
                    添加人员
                  </Button>,
                ]}
              />
              <Filter
                form={filterForm}
                initialValues={{
                  pageNum: 1,
                  pageSize: 10,
                }}
                onSearch={() => {
                  _fetch.users(
                    curSelectDepartmentId,
                    filterForm.getFieldsValue(true),
                  );
                }}
                onReset={() => {
                  _fetch.users(
                    curSelectDepartmentId,
                    filterForm.getFieldsValue(true),
                  );
                }}
              >
                <Form.Item label={"姓名"} name={"name"}>
                  <Input />
                </Form.Item>
              </Filter>
              <div className="h-full w-full">
                <Table
                  loading={loading}
                  scroll={{
                    y: tableHeight,
                    x: "max-content",
                  }}
                  rowKey={(record) => record.id}
                  columns={_ui.tableColumns}
                  dataSource={userList?.list || []}
                  locale={{
                    emptyText: "暂无数据",
                  }}
                  pagination={{
                    showTotal: (total, range) => {
                      return `共 ${total} 条`;
                    },
                    pageSizeOptions: [10, 20, 50, 100],
                    defaultPageSize: 100,
                    showSizeChanger: true,
                    onChange(page, pageSize) {
                      filterForm.setFieldsValue({
                        pageNum: page,
                        pageSize: pageSize,
                      });
                      _fetch.users(
                        curSelectDepartmentId,
                        filterForm.getFieldsValue(true),
                      );
                    },
                    pageSize: userList?.pageSize,
                    current: userList?.pageNum,
                    total: userList?.total,
                  }}
                />
              </div>
            </>
          ) : (
            <Empty icon={UserIcon} title="请选择左侧部门进行操作" />
          )}
        </div>
      </div>
      <UserEmployeeModal
        visible={modalVisible}
        userEmployee={editUserEmployee}
        onCancel={() => {
          setModalVisible(false);
          setEditUserEmployee(null);
        }}
        onOk={() => {
          setModalVisible(false);
          _fetch.users(curSelectDepartmentId, filterForm.getFieldsValue(true));
        }}
      />
    </>
  );
}
